import path from 'path';
import * as fs from 'node:fs/promises';

export interface PostDetail {
  date: string;
  spoiler: string;
  title: string;
  id: string;
  content: string;
  birthtime: Date;
  atime: Date;
  mtime: Date;
  ctime: Date;
}

const rootDirectory = path.join(process.cwd(), 'app', 'posts');

export const getPostBySlug = async (dir: string) => {
  const filePath = path.join(rootDirectory, dir, '/index.mdx');

  const fileContent = await fs.readFile(filePath, { encoding: 'utf8' });
  const stat = await fs.stat(filePath);

  const id = Buffer.from(dir, 'utf-8').toString('hex');

  return {
    id,
    title: dir,
    content: fileContent,
    birthtime: stat.birthtime, //创建时间
    atime: stat.atime, //最近被访问时间
    mtime: stat.mtime, //最近被编辑时间
    ctime: stat.ctime, // 修改时间 任何修改 包括权限等
  } as PostDetail;
};

export const getAllPostsMeta = async (query: string, currentPage: number) => {
  const files = await fs.readdir(rootDirectory, { withFileTypes: true });
  const dirs = files
    .filter((entry) => entry.isDirectory())
    .map((entry) => entry.name);

  let list = await Promise.all(
    dirs.map(async (dir) => {
      return await getPostBySlug(dir);
    }),
  );

  list.sort((a, b) => {
    return Date.parse(a.date) < Date.parse(b.date) ? 1 : -1;
  });
  return list.filter((item) => item.title.includes(query));
};

export async function getPost(id: string) {
  const posts = await getAllPostsMeta('', 0);
  if (!id) throw new Error('not found');
  const post = posts.find((post) => post.id === id);
  return post;
}
